"use strict";
// emailBox automatic login
// 2018-11-15

var gInUse = true;
var gData = [];

$(document).ready(function () {
	
	//chrome.storage.sync.clear();
	
	chrome.storage.sync.set({'inuse':true}, function(){
		debugLog("set default switch on");
	});
	
	chrome.storage.sync.get(['url', 'name', 'pwd'], function(data){
		// gData['url'] = data.url;
		// gData['name'] = data.name;
		// gData['pwd'] = data.pwd;
		
		gData = data;
		
		debugLog('url:' + data.url);
		debugLog('name:' + data.name);
		
		if (!data.url) {
			chrome.storage.sync.set({'url':'mail.pwrd.com/owa/auth/logon.aspx'}, function(){
				debugLog("init data.url=mail.pwrd.com/owa/auth/logon.aspx");
			});
		}
	});
	
	chrome.storage.onChanged.addListener(function(changes, namespace) {
		for (var key in changes) {
			var storageChange = changes[key];
			
			gData[key] = storageChange.newValue;
			
			debugLog('key:' + key + ',from:' + storageChange.oldValue + ',changeTo:' + storageChange.newValue);
			
			if ('inuse' == key) {
				gInUse = storageChange.newValue;
			}
		}
	});
});

chrome.tabs.onCreated.addListener(function(tab) {
	debugLog('onCreated id:' + tab.id + ', tab.url:' + tab.url);
});

//var freezeTime = new Date();

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
	debugLog('onUpdated tabId:' + tabId + ',tab.status:' + tab.status + ',changeInfo:' + changeInfo + ',tab.url:' + tab.url);
	
	if (!gInUse) {
		debugLog('The plugin has been disabled.');
		return ;
	}
	
	if (tab.status == 'complete') {
		//debugLog('url[' + tab.url + ']load complete!');
		
		if (tab.url.indexOf(gData.url) != -1) {
			chrome.tabs.executeScript(tab.id, {file: "jquery-1.11.2.min.js"}, function() {
				//debugLog("excuteScript:jquery-1.11.2.min.js");
				chrome.tabs.executeScript(tab.id, {file: "ContentScript_Login.js"}, function() {
					debugLog("excuteScript:ContentScript_Login.js");
				});
			});
		}
	}
	
	//var now = new Date();
	//if (freezeTime.getTime() + 1000 < now.getTime()) {
		// if (tab.status == 'complete') {
			// //debugLog('url[' + tab.url + ']load complete!');
			
			// if (tab.url.indexOf(gData.url) != -1) {
				// //debugLog('url[' + tab.url + ']load complete and excuteScript.');
				
				// // 邮箱登录页面
				// freezeTime = new Date();
				
				// chrome.tabs.executeScript(tab.id, {file: "jquery-1.11.2.min.js"}, function() {
					// //debugLog("excuteScript:jquery-1.11.2.min.js");
					// chrome.tabs.executeScript(tab.id, {file: "ContentScript_Login.js"}, function() {
						// debugLog("excuteScript:ContentScript_Login.js");
					// });
				// });
			// }
		// }
	//}
});

// 消息监听
chrome.extension.onConnect.addListener(function(port) {
	port.onMessage.addListener(function(msg) {
		debugLog("mtype:" + msg.mtype);
		
		if ('get' == msg.mtype) {
			if (gData.name && gData.pwd) {
				port.postMessage({name:gData.name, pwd:gData.pwd});
				debugLog("return name:" + gData.name);
			}
		} else if ('visit' == msg.mtype) {
			chrome.tabs.create( {url : 'https://mail.pwrd.com/owa/auth/logon.aspx'}, function(tab) {
				console.log('createTab:' + tab.id);
			});
		}
		
	});
});

////////////////////////////////////////////////////////////////
// 工具函数
////////////////////////////////////////////////////////////////
var g_logCount = 0;
function debugLog(log) {
	var nowTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
	console.log('[' + nowTime + '][' + (++g_logCount) + ']' + log);
}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

// 等待函数
function sleep(numberMillis) { 
var now = new Date(); 
var exitTime = now.getTime() + numberMillis; 
while (true) { 
now = new Date(); 
if (now.getTime() > exitTime) 
return; 
} 
}
